package com.yashi.springmvcjbpm.controller;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.jbpm.api.ProcessInstance;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.yashi.springmvcjbpm.mail.Main;
import com.yashi.springmvcjbpm.service.impl.JBPMServiceImpl;
import com.yashi.springmvcjbpm.service.impl.RuleServiceimpl;

@Controller
public class RequestController {
	private final static String resourceName = "rules/leave.jpdl.xml";
	private final static String resourceImgName = "rules/leave.png";
	private JBPMServiceImpl jbpmServiceImpl = new JBPMServiceImpl();
	private Main main = new Main();
	@RequestMapping(value = "/requestAction", method = RequestMethod.POST)
	public String execute(HttpServletRequest request) throws UnsupportedEncodingException {
		String leaveLong = (String) request.getParameter("leaveLong");
		leaveLong = new String(leaveLong.getBytes("ISO-8859-1"), "UTF-8");// 对乱码进行处理
		String leaveContent = (String) request.getParameter("leaveContent");
		leaveContent = new String(leaveContent.getBytes("ISO-8859-1"), "UTF-8");// 对乱码进行处理
		String staffName = (String) request.getSession().getAttribute("staffName");

		if (jbpmServiceImpl.getAllPd().size() == 0) { // 如果还没有流程定义则发布
			System.out.println("resourcesName===="+resourceName);
			String processDefineId=jbpmServiceImpl.deployNew(resourceName,resourceImgName);
			System.out.println("processDefineId="+processDefineId);
		}
		String pdId = jbpmServiceImpl.getAllPd().get(0).getId(); // 获得第一个Id
		System.out.println("pdid="+pdId);
		ProcessInstance processInstance = jbpmServiceImpl.startPI(staffName, pdId); // 开始流程实例
//		leaveLong = RuleServiceimpl.changeVale(leaveLong);
//		System.out.println("leaveLong=" + leaveLong);
		jbpmServiceImpl.applyLeave(staffName, leaveLong, leaveContent, processInstance.getId()); // 添加进入数据库
		jbpmServiceImpl.completeTask(jbpmServiceImpl.getTaskId(staffName), leaveLong, leaveContent); // 完成任务
		main.sendMail(staffName);
		return "index";

	}

	// 处理被驳回的请求
	@RequestMapping(value = "/reRequestAction")
	public String reRequest(String taskId, String leaveLong, String leaveContent) throws UnsupportedEncodingException {

		leaveLong = new String(leaveLong.getBytes("ISO-8859-1"), "UTF-8");// 对乱码进行处理
//		leaveLong = RuleServiceimpl.changeVale(leaveLong);
		leaveContent = new String(leaveContent.getBytes("ISO-8859-1"), "UTF-8");// 对乱码进行处理
		System.out.println("taskId=" + taskId + ",long=" + leaveLong + ",content=" + leaveContent);
		Map leave = (Map) jbpmServiceImpl.getLeaveDetail(taskId).get(0);
		jbpmServiceImpl.updateLeave(leave, leaveLong, leaveContent);
//		jbpmServiceImpl.completeTask(taskId);
		jbpmServiceImpl.completeTask(taskId, leaveLong, leaveContent); // 完成任务
		return "index";
	}
}
